package com.iflyteck.handler;

import com.iflyteck.pojo.RpcRequest;
import com.iflyteck.utils.SpringContextUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Lazy(false)
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    // 当客户端读取数据时，该方法就会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //注意：客户端将发送请求的时候会传递一个参数：UserService#sayHello#are you ok
        //1、判断当前用户是否符合请求规则
        if(msg instanceof RpcRequest) {
            // 2、如果符合规则，调用实现类返回一个result
            // 通过spring容器获取到要执行的bean对象
            RpcRequest rpcRequest = (RpcRequest)msg;
            Object bean = applicationContext.getBean(rpcRequest.getClassName());
            // UserServiceImpl userService = new UserServiceImpl();
            Class<?> clazz = bean.getClass();
            Method method = clazz.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
            Object result = method.invoke(bean, rpcRequest.getParameters());
            ctx.writeAndFlush(result);
        }
    }


}
